package com.xiyi.shouxin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.xiyi.shouxin.dao.user.MusicRepository;
import com.xiyi.shouxin.entity.user.Music;
import com.xiyi.shouxin.entity.user.mapper.MusicMapper;
import com.xiyi.shouxin.exception.CommonException;
import com.xiyi.shouxin.exception.ErrorCode;
import com.xiyi.shouxin.view.pojo.ItemPage;
import com.xiyi.shouxin.view.pojo.MusicView;

@Service
public class MusicService {
    @Autowired
    private MusicRepository musicRepository;

    /*
     * 音乐列表
     */
    public ItemPage<MusicView> findMusicList(String name, int page, int size) throws Exception {
        List<MusicView> list = new ArrayList<>();
        List<Music> result = new ArrayList<>();
        int total = 0;
        Sort sort = Sort.by(Direction.DESC, "id");
        result = musicRepository.findByMultiConditionsByPage(name, sort, page, size);
        total = musicRepository.countByMultiConditions(name);
        for (Music music : result) {
            list.add(new MusicView(music));
        }
        return new ItemPage<MusicView>(list, total);
    }

    /*
     * 音乐详情
     */
    public MusicView findMusic(Long musicId) throws Exception {
        Music music = musicRepository.findById(musicId, new MusicMapper());
        if (music != null) {
            return new MusicView(music);
        }
        throw new CommonException(ErrorCode.NOTFOUND);
    }

    /*
     * 添加音乐
     */
    public MusicView createMusic(Music music) throws Exception {
        if (music == null || !StringUtils.hasText(music.getName())) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        music.setCreatedAt(new Date());
        Long id = musicRepository.create(music);
        music.setId(id);
        return new MusicView(music);
    }

    /*
     * 修改音乐
     */
    public void updateMusic(Music music) throws Exception {
        if (music == null || music.getId() == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }

        musicRepository.update(music.getId(), music);
    }

    /*
     * 删除音乐
     */
    public void delMusics(List<Long> musicIds) throws CommonException {
        if (musicIds == null || musicIds.isEmpty()) {
            return;
        }
        musicRepository.delByIds(musicIds);
    }

}
